package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisCacheUtil;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisCacheUtil redisCacheUtil;

    //使用 StringRedisTemplate 操作 Redis 时，所有键（Key）和值（Value）都会以 字符串形式（String） 存储和读取。
    // 因此，在存储对象时需要将对象序列化为 JSON 字符串，查询时再将 JSON 字符串反序列化为 Java 对象。

    @Override
    public Result queryById(Long id) {
        //缓存穿透
        Shop shop = redisCacheUtil.HuanCunChuanTou(RedisConstants.CACHE_SHOP_KEY,id, Shop.class,this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //缓存击穿
        //Shop shop = redisCacheUtil.HuanCunJiChuan(RedisConstants.CACHE_SHOP_KEY,id, Shop.class,this::getById, 10L, TimeUnit.SECONDS);
        if(shop == null){
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    //缓存击穿
    public Shop queryWithMutex(Long id){
        //从redis中查询商铺缓存
        String json = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        //判断是否存在
        if(StrUtil.isNotBlank(json)){  //isNotBlank()判断字符串 字符串为null,"",换行符都是false 只有有数据时才为true
            //存在 转为对象并返回
            Shop shop = JSONUtil.toBean(json, Shop.class);
            return shop;
        }
        //判断命中是否是空值
        if(json!=null){
            return null;
        }

        //实现缓存重建
        //获取互斥锁
        String lock = RedisConstants.LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            boolean tryLock = tryLock(lock);
            //判断是否获取锁成功
            if(!tryLock){
                //失败 则休眠
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //获取锁成功
            //Double Check：其他线程可能已更新缓存，再次检查
            String latestJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
            if (StrUtil.isNotBlank(latestJson)) {
                return JSONUtil.toBean(latestJson, Shop.class);
            }
            shop = super.getById(id);
            //不存在
            if(shop == null){
                //将空值写入redis
                stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "",RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //将查询到的信息存入redis
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            //释放互斥锁
            unLock(lock);
        }
        //返回
        return shop;
    }

    //获取锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    //释放锁
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }


    //缓存穿透
    public Shop queryWithPassThrough(Long id){
        //从redis中查询商铺缓存
        String json = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        //判断是否存在
        if(StrUtil.isNotBlank(json)){
            //存在 转为对象并返回
            Shop shop = JSONUtil.toBean(json, Shop.class);
            return shop;
        }
        //判断命中是否是空值
        if(json!=null){
            return null;
        }

        //若不存在 查询数据库
        Shop shop = super.getById(id);
        //不存在 则返回错误
        if(shop == null){
            //将空值写入redis
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "",RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //将查询到的信息存入redis
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //返回
        return shop;
    }




    //更新店铺信息
    @Override
    @Transactional
    public Result update(Shop shop) {
        if(shop.getId() == null){
            return Result.fail("店铺id为空");
        }
        //更新数据库
        super.updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }
}
